package com.shxc.smarttrade.old.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.ViewPagerAdapter;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.FollowMasterIndex;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.CustomTextView;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/9/26.
 */

public class OrderSupervisorFragment extends Fragment {
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.tv_all_profit)
    TextView tvAllProfit;
    @BindView(R.id.tv_mt4_id)
    TextView tvMt4Id;
    @BindView(R.id.tv_profits)
    TextView tvProfits;
    @BindView(R.id.tv_follow_history)
    TextView tvFollowHistory;
    @BindView(R.id.customTextView)
    CustomTextView customTextView;
    @BindView(R.id.tv_account_divide)
    TextView tvAccountDivide;
    @BindView(R.id.tv_detail_msg)
    CustomTextView tvDetailMsg;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    private View rootView;
    private static final String[] tabName = {"跟随中", "已取消", "分成记录"};
    private List<String> mDataList = Arrays.asList(tabName);

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    FollowMasterIndex.DataBean.StatisBean statisBean = (FollowMasterIndex.DataBean.StatisBean) msg.obj;
                    tvAllProfit.setText("$" + BaseUtils.getDigitsData(statisBean.getSumProfit(), 2));
                    tvMt4Id.setText(String.valueOf(statisBean.getMt4Id()));
                    tvProfits.setText(statisBean.getSumCopy() + "人");
                    tvFollowHistory.setText("$" + BaseUtils.getDigitsData(statisBean.getLastSumPay(), 2));
                    tvAccountDivide.setText("$" + BaseUtils.getDigitsData(statisBean.getSumPay(), 2));
                    tvDetailMsg.setText("当前跟单人数：" + statisBean.getCurrentCopyNum() + "人；已取消：" + statisBean.getCannelCopyNum() + "人。");
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_order_supervisor, null);
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null)
            parent.removeView(rootView);

        ButterKnife.bind(this, rootView);
        initView();
        initData();
        initListener();
        return rootView;
    }

    private void initListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getFollowMasterIndex();
            }
        });
    }

    private void initView() {
        EventBus.getDefault().register(this);
        swipeRefreshLayout.setColorSchemeColors(Color.RED,
                Color.argb(255, 216, 155, 60),
                Color.RED,
                Color.argb(255, 216, 155, 60));

        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new FollowListFragment());
        fragmentList.add(new FollowCancelListFragment());
        fragmentList.add(new FollowDivideListFragment());

        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), fragmentList));
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataList.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#666666"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#ff6200"));
//                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 5.2f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        magicIndicator.onPageSelected(i);
//                        commonNavigator.onPageSelected(i);
//                        commonNavigator.onAttachToMagicIndicator();
                        viewPager.setCurrentItem(i);
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#ff6200")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));
                indicator.setLineWidth(BaseUtils.dip2px(context, 60));
                indicator.setRoundRadius(2);
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
//                indicator.setYOffset(UIUtil.dip2px(context, 39));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerPadding(UIUtil.dip2px(getActivity(), 5));
        titleContainer.setDividerDrawable(getResources().getDrawable(R.drawable.simple_splitter));
        ViewPagerHelper.bind(magicIndicator, viewPager);
    }

    private void initData() {
        showDialog();
        getFollowMasterIndex();
    }

    private void getFollowMasterIndex() {
        Map<String, Object> map = new HashMap<>();
        if (getActivity() != null)
            map.put("accessToken", SpUtils.getString(getActivity(), "accessToken", ""));
        map.put("userId", String.valueOf(SpUtils.getInt(getActivity(), "userId", -1)));
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.FOLLOW_MASTER_INDEX, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showMyToasts("网络异常");
                dissmissDialog();
                if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void success(String response, int id) {
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    return;
                }
                Gson gson = new Gson();
                FollowMasterIndex followMasterIndex = gson.fromJson(response, FollowMasterIndex.class);
                if (followMasterIndex.getErr_code().equals("0")) {
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = followMasterIndex.getData().getStatis();
                    handler.sendMessage(msg);
                } else {
                    showMyToasts(followMasterIndex.getErr_msg());
                }
                if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(false);
                dissmissDialog();

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    public void showMyToasts(String str) {
        if (getActivity() != null)
            MyApplication.showToast(getActivity(), str);
    }

    private MyProgressDialog progressDialog;

    public void showDialog() {
        if (progressDialog == null) {
            progressDialog = new MyProgressDialog(getActivity());
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    public void dissmissDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.FOLLOW_ORDER_DETAIL_ACTIVITY)) {
            getFollowMasterIndex();
        }
    }
}
